package com.kzw.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import my.mvc.MultipartRequest;
import my.mvc.RequestContext;
import my.util.ResponseUtils;
import my.util.ServletUtils;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import com.kzw.dao.support.Page;
import com.kzw.entity.Clazz;
import com.kzw.entity.Student;
import com.kzw.json.Jackson;
import com.kzw.service.ClazzService;
import com.kzw.service.StudentService;

public class StudentAction {

	private ClazzService clazzService = new ClazzService();
	private StudentService studentService = new StudentService();

	
	/**
	 * 增加之前，获得班级列表
	 * */
	public void addUI(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		List<Clazz> clazzList = clazzService.findAll();
		req.setAttribute("clazzList", clazzList);
		req.getRequestDispatcher("/pages/student_form.jsp").forward(req, resp);
	}
	
	/**
	 * 编辑之前，获得班级列表和学生信息
	 * */
	public void editUI(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		List<Clazz> clazzList = clazzService.findAll();
		req.setAttribute("clazzList", clazzList);
		
		String id = req.getParameter("id");
		Student student = studentService.findById(Long.parseLong(id));
		req.setAttribute("student", student);
		
		req.getRequestDispatcher("/pages/student_form.jsp").forward(req, resp);
	}
	
	/**
	 * 增加学生或修改学生
	 * */
	public void save(RequestContext rc) throws ServletException, IOException {
		
		// 普通字段
		Student student = rc.form(Student.class);
		
		// 文件字段
		MultipartRequest multiReq = (MultipartRequest)(rc.request());
		File file = multiReq.getFile("myfile");
		System.out.println(file.getName());
		InputStream is = new FileInputStream(file); 
		
		// 文件输出流
		String upload = rc.context().getRealPath("/upload");
		System.out.println(upload);
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String fname = uuid + "." + FilenameUtils.getExtension(file.getName());
		FileOutputStream fos = new FileOutputStream(new File(upload, fname));
		
		// 将输入流写到输出流中
		IOUtils.copy(is, fos);
		is.close();
		fos.close();
		
		// 手动设置
		student.setPicPath(fname);
		
		if(student.getId() == 0) {
			studentService.add(student);
		} else {
			studentService.update(student);
		}
		
		// 重定向到一个查询请求
		rc.redirect(rc.contextPath() + "/action/student/list");
	}
	

	/**
	 * 学生列表
	 * */
	public void list(RequestContext rc) throws ServletException, IOException {
		
		String name = rc.request().getParameter("name");
		System.out.println(name);
		
		// 当前第几页
		int pageNo = rc.param("pageNo", 1);
		Page<Student> page = new Page<>(10);
		page.setPageNo(pageNo);
		
		studentService.findPage(page);
		rc.reqAttr("page", page);
		// 服务器端跳转
		rc.forward("/pages/student_list.jsp");	
	}
	

	/**
	 * 班级列表: ajax请求，没有页面跳转的
	 * */
	public void ajax(RequestContext rc) throws ServletException, IOException {
		List<Clazz> clazzList = clazzService.findAll();
		String json = Jackson.me().without(Clazz.class, "note").toJson(clazzList);
		ResponseUtils.renderJson(rc.response(), json);
	}
	
	/**
	 * 文件下载
	 * */
	public void downImg(RequestContext rc) throws ServletException, IOException {
		long id = rc.param("id", 0L);
		Student student = studentService.findById(id);
		String picPath = student.getPicPath();
		String upload = rc.context().getRealPath("/upload");
		File file = new File(upload, picPath);
		InputStream is = new FileInputStream(file);
		
		// 输出流
		OutputStream os = rc.response().getOutputStream();		
		// 设置文件下载时, response的头信息
		ServletUtils.setFileDownloadHeader(rc.response(), picPath);
		
		// 如果文件比较大，则需要以下方式处理
		int len;
		byte[] buf = new byte[1024];
		while((len=is.read(buf)) > 0) {
			os.write(buf, 0, len);
		}
		is.close();
		os.close();		
	}
	
	/**
	 * 使用servlet3进行文件上传
	 * */
	public void save2(RequestContext rc) throws ServletException, IOException {
		
		// 普通字段
		Student student = rc.form(Student.class);
		
		Collection<Part> parts = rc.request().getParts();
		for(Part part : parts) {
			String name = part.getName();
			System.out.println(name);
			
			// 获得文件原始名称
			Collection<String> names = part.getHeaderNames();
			for(String head  : names) {
				System.out.println(part.getHeader(head));
			}
			
			InputStream is = part.getInputStream();
			// 将输入流写到文件输出流
			
		}
		
//		// 文件字段
//		MultipartRequest multiReq = (MultipartRequest)(rc.request());
//		File file = multiReq.getFile("myfile");
//		System.out.println(file.getName());
//		InputStream is = new FileInputStream(file); 
//		
//		// 文件输出流
//		String upload = rc.context().getRealPath("/upload");
//		System.out.println(upload);
//		String uuid = UUID.randomUUID().toString().replace("-", "");
//		String fname = uuid + "." + FilenameUtils.getExtension(file.getName());
//		FileOutputStream fos = new FileOutputStream(new File(upload, fname));
//		
//		// 将输入流写到输出流中
//		IOUtils.copy(is, fos);
//		is.close();
//		fos.close();
//		
//		// 手动设置
//		student.setPicPath(fname);
//		
//		if(student.getId() == 0) {
//			studentService.add(student);
//		} else {
//			studentService.update(student);
//		}
		
		// 重定向到一个查询请求
		rc.redirect(rc.contextPath() + "/action/student/list");
	}
}
